<template>
  <div>
    <el-dialog
      :title="info.isadd?'商品管理添加':'商品管理修改'"
      :visible.sync="info.isshow"
      @opened="opened"
      @closed="closed"
      @close="close"
    >
      {{form}}
      <el-form :model="form">
        <el-form-item label="一级分类" label-width="120px">
          <el-select placeholder="请选择" v-model="form.first_cateid" @change="erji">
            <el-option
              v-for="item in catelist"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="二级分类" label-width="120px">
          <el-select placeholder="请选择" v-model="form.second_cateid">
            <el-option
              v-for="item in secondCateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品名称" label-width="120px">
          <el-input v-model="form.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="120px">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" label-width="120px">
          <el-input v-model="form.market_price" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="图片" label-width="120px">
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :on-change="upload">
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品规格" label-width="120px">
          <el-select placeholder="请选择" v-model="form.specsid" @change="guigeerji">
            <el-option
              v-for="item in specsList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格属性" label-width="120px">
          <el-select placeholder="请选择" multiple v-model="form.specsattr">
            <el-option v-for="item in attrsArr" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否新品" label-width="120px">
          <template>
            <el-radio v-model="form.isnew" :label="1">是</el-radio>
            <el-radio v-model="form.isnew" :label="2">否</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="热卖" label-width="120px">
          <template>
            <el-radio v-model="form.ishot" :label="1">是</el-radio>
            <el-radio v-model="form.ishot" :label="2">否</el-radio>
          </template>
        </el-form-item>

        <el-form-item label="状态" label-width="120px">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="2"></el-switch>
        </el-form-item>

        <el-form-item label="商品描述" label-width="120px">
          <!-- 二、富文本编辑器  添加了条件渲染-->
          <div id="editor" v-if="info.isshow"></div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="qx">取 消</el-button>
        <el-button type="primary" v-if="info.isadd" @click="add">添 加</el-button>
        <el-button type="primary" v-else @click="update">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import E from "wangeditor";
import {
  reqcatelist,
  reqgoodsadd,
  reqgoodsinfo,
  reqgoodsedit,
} from "../../../request/api";
import { errorAlert, successAlert } from "../../../utils/alert";
import { mapActions, mapGetters } from "vuex";
import path from "path";
export default {
  props: ["info"],
  data() {
    return {
      imgUrl: "",
      form: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 2,
        ishot: 2,
        status: 2,
      },
      secondCateList: [], //二级分类

      attrsArr: [], //规格属性二级分类
    };
  },
  computed: {
    ...mapGetters({
      catelist: "cate/list", //商品列表
      specsList: "specs/list", //商品规格列表
    }),
  },
  mounted() {
    if (this.catelist.length === 0) {
      this.reqlist();
    }
    this.reqSpecsList(true);
  },
  methods: {
    ...mapActions({
      reqlist: "cate/reqlist", //请求商品列表
      reqSpecsList: "specs/reqlist", //请求分类列表
      reqgoodList: "goods/reqList",
      reqCount: "goods/reqCount",
    }),

    //创建编辑器
    opened() {
      //创建一个编辑器
      this.editor = new E("#editor");
      this.editor.create();
      //给编辑器赋值
      this.editor.txt.html(this.form.description);
    },
    close() {
      this.form.description = this.editor.txt.html();
    },
    //二级分类

    erji() {
      //获取二级列表
      this.form.second_cateid = "";
      this.qerji();
    },
    qerji() {
      reqcatelist({
        pid: this.form.first_cateid,
      }).then((res) => {
        if (res.data.code == 200) {
          this.secondCateList = res.data.list ? res.data.list : [];
        }
      });
    },
    //规格属性二级分类
    guigeerji() {
      this.form.specsattr = [];
      this.getAttrsArr();
    },
    getAttrsArr() {
      let obj = this.specsList.find((item) => item.id == this.form.specsid);
      this.attrsArr = obj ? obj.attrs : [];
    },
    closed() {
      if (!this.info.isadd) {
        this.emity();
      }
    },
    //清空
    emity() {
      this.form = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 2,
        ishot: 2,
        status: 2,
      };
      this.secondCateList = [];
      this.attrsArr = [];
      this.imgUrl = "";
    },
    qx() {
      this.info.isshow = false;
    },
    //上传图片
    upload(e) {
      let file = e.raw;
      // console.log(file);
      if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件最大2M");
        return;
      }
      let imgArr = [".jpg", ".jpeg", ".png", ".gif"];
      let extname = path.extname(file.name);
      if (!imgArr.includes(extname)) {
        errorAlert("请上传正确的图片格式");
        return;
      }
      this.imgUrl = URL.createObjectURL(file);
      this.form.img = file;
    },
    checkEmpty() {
      return new Promise((resolve, reject) => {
        if (this.form.first_cateid == "") {
          errorAlert("一级分类不能为空");
          return;
        }
        if (this.form.second_cateid == "") {
          errorAlert("二级分类不能为空");
          return;
        }
        if (this.form.goodsname == "") {
          errorAlert("商品名称不能为空");
          return;
        }
        if (this.form.price == "") {
          errorAlert("价格不能为空");
          return;
        }
        if (this.form.market_price == "") {
          errorAlert("市场价格不能为空");
          return;
        }
        if (!this.form.img) {
          errorAlert("图片不能为空");
          return;
        }
        if (this.form.specsid == "") {
          errorAlert("规格不能为空");
          return;
        }
        if (this.form.specsattr.length == 0) {
          errorAlert("规格属性不能为空");
          return;
        }
        if (this.editor.txt.html() === "") {
          errorAlert("描述不能空");
          return;
        }
        resolve();
      });
    },
    add() {
      this.checkEmpty().then(() => {
        reqgoodsadd({
          ...this.form,
          specsattr: this.form.specsattr.join(","),
          description: this.editor.txt.html(),
        }).then((res) => {
          console.log(res);
          if (res.data.code == 200) {
            successAlert(res.data.msg);
            this.emity();
            this.qx();
            this.reqgoodList();
            this.reqCount();
          }
        });
      });
    },

    getOne(id) {
      reqgoodsinfo({ id: id }).then((res) => {
        if (res.data.code == 200) {
          this.form = res.data.list;
          this.form.id = id;
          this.imgUrl = this.$pre + this.form.img;
          this.qerji();
          this.form.specsattr = this.form.specsattr.split(",");
          this.getAttrsArr();
          if (!!this.editor) {
            this.editor.txt.html(this.form.description);
          }
        }
      });
    },
    update() {
      this.checkEmpty().then(() => {
        reqgoodsedit({
          ...this.form,
          specsattr: this.form.specsattr.join(","),
          description: this.editor.txt.html(),
        }).then((res) => {
          if (res.data.code == 200) {
            successAlert(res.data.msg);
            this.qx();
            this.emity();
            this.reqgoodList();
          }
        });
      });
    },
  },
};
</script>

<style scoped>
.avatar-uploader /deep/.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>